package com.qf.controller;

import com.qf.mapper.TicketMapper;
import com.qf.pojo.Ticket;
import com.qf.utils.ThreadUtiils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

//@RestController
//@RequestMapping("/ticket")
public class TicketController {

    @Autowired
    private TicketMapper ticketMapper;

    @Value("${winnum}")
    private Integer winnum;


    @GetMapping("/sell/{id}")
    public void sell(@PathVariable("id") Integer id){
        while (true){
            //查询对应id的票数
            //锁对象要保证唯一 (两个人买相同车次的票，才需要锁互斥；两个人买的是不同车次票，不需要互斥)
            //在多机集群环境下，这个synchronized本地所无法保证锁对象唯一，所以锁会失效
            //此时，在集群环境下需要保障多进程操作共享数据的安全，需要使用【分布式锁】。
            synchronized (id) {
                Ticket ticket = ticketMapper.selectById(id);

                if (ticket.getCount() > 0) {
                    System.out.println(winnum + "号窗口正在卖出第：" + ticket.getCount() + "张票");

                    //模拟卖票的时间
                    ThreadUtiils.sleep(1000);

                    //更新票数
                    int count = ticket.getCount() - 1;
                    ticket.setCount(count);
                    //更新数据库
                    ticketMapper.updateById(ticket);

                    System.out.println(winnum + "号窗口剩余票数为：" + count);
                } else {
                    break;
                }
            }
        }
    }


    public void method1(){
        synchronized (this){
            System.out.println("------");
            method2();
        }
    }

    public synchronized void method2(){
        System.out.println("222222222");
    }

}
